package com.akino.gulimall.member.service.impl;

import com.akino.gulimall.member.dao.MemberLevelDao;
import com.akino.gulimall.member.entity.MemberLevelEntity;
import com.akino.gulimall.member.vo.MemberLoginVo;
import com.akino.gulimall.member.vo.MemberRegistVo;
import com.akino.gulimall.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.akino.common.utils.PageUtils;
import com.akino.common.utils.Query;

import com.akino.gulimall.member.dao.MemberDao;
import com.akino.gulimall.member.entity.MemberEntity;
import com.akino.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<String> regist(MemberRegistVo vo) {
        List<String> strings = new ArrayList<>();
        MemberEntity entity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;
        // 设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());
        // 检查用户名和手机号是否唯一
        if (checkMobileUnique(vo.getMobile())) {
            // 设置手机号
            entity.setMobile(vo.getMobile());
        } else {
            strings.add("手机号不唯一");
        }
        if (checkUsernameUnique(vo.getUserName())) {
            // 设置用户名
            entity.setUsername(vo.getUserName());
        } else {
            strings.add("用户名不唯一");
        }
        // 设置密码（向数据库里存放加密后的密码）
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        // TODO 设置其他默认信息

        if (strings.isEmpty()) {
            memberDao.insert(entity);
        }
        return strings;
    }

    /**
     * 检查用户名和手机号是否唯一
     * @param mobile
     * @return
     */
    @Override
    public boolean checkMobileUnique(String mobile) {
        MemberDao baseMapper = this.baseMapper;
        if (baseMapper
                .selectCount(new QueryWrapper<MemberEntity>()
                        .eq("mobile",mobile))>0){
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUsernameUnique(String username) {
        MemberDao baseMapper = this.baseMapper;
        if (baseMapper
                .selectCount(new QueryWrapper<MemberEntity>()
                        .eq("username",username))>0){
            return false;
        }
        return true;
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();
        // 去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (memberEntity == null) {
            return null;
        }
        // 获取到数据库的password
        String passwordDB = memberEntity.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 进行密码匹配
        boolean matches = passwordEncoder.matches(password, passwordDB);
        if (matches){
            return null;
        }
        return memberEntity;
    }

    /**
     * 用第三方社交账号登陆
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        // 登陆和注册合并逻辑
        String uid = socialUser.getUid();
        // 1.判断当前社交用户是否已经登陆过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null){
            // 用户已经注册过，更换令牌access_token和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getRemind_in());

            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getRemind_in());
            return memberEntity;
        }
        // 没有查到当前社交用户，注册一个
        MemberEntity regist = new MemberEntity();
        // TODO 用auth-server服务查询当前社交用户的社交账号信息，发送给Member服务

        return null;
    }

}